﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.IO;

namespace FSC.HaNamAPApplication
{
    public partial class HNAP_AdminDocEdit : System.Web.UI.UserControl
    {
        private string modeform
        {
            get
            {
                string modeform = "a";
                if (Request.QueryString["m"] != null && Request.QueryString["m"].ToString() != "")
                {
                    modeform = Request.QueryString["m"].ToString();
                }
                return modeform;
            }
        }

        private int docId
        {
            get
            {
                int docId = -1;
                if (Request.QueryString["did"] != null && int.TryParse(Request.QueryString["did"].ToString(), out docId))
                {
                    docId = int.Parse(Request.QueryString["did"].ToString());
                }
                return docId;
            }
        }

        public string CurrentUrlWithoutParam
        {
            get
            {
                return Controler.UrlWithoutParam(Request.RawUrl);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDrop();

                if (this.modeform.Equals("u"))
                {
                    LoadData();
                }
                else
                {
                    divAttachFile.Visible = false;
                    fupAttach.Visible = true;
                }
            }
        }

        /// <summary>
        /// Update a attach file into 'Documents' document libraries of sharepoint.
        /// </summary>
        private string UploadFiles()
        {
            string result = "";
            
            SPSite objSite = SPControl.GetContextSite(Context);
            SPWeb objWeb = objSite.OpenWeb();
            objWeb.AllowUnsafeUpdates = true;
            SPList objList = objWeb.Lists["Documents"];

            SPDocumentLibrary objLib = null;
            objLib = (SPDocumentLibrary)objList;
            SPFolder rFolder = objLib.RootFolder;

            if (fupAttach.HasFile)
            {
                SPFile objFile = null;
                byte[] byteArr = null;

                Stream fStream = fupAttach.PostedFile.InputStream;
                byteArr = new byte[fStream.Length];
                fStream.Read(byteArr, 0, (int)fStream.Length);
                fStream.Close();

                objFile = rFolder.Files.Add(rFolder.Url + "/" + fupAttach.PostedFile.FileName + "", byteArr, true);
                objFile.Update();

                //objAPF.Name = (Request.Form["fText" + i].ToString().Trim() != "") ? Request.Form["fText" + i].ToString() : userPostedFile.FileName;
                result = GetUrlWithoutDomain(rFolder.ParentWeb.Url + "/" + rFolder.Url) + "/" + fupAttach.PostedFile.FileName;

                //Test
                //Response.Write(GetUrlWithoutDomain(rFolder.ParentWeb.Url + "/" + rFolder.Url) + "/" + userPostedFile.FileName);
            }
            return result;
        }

        /// <summary>
        /// Deleting item from document libraries in Sharepoint
        /// </summary>
        /// <param name="web">This is the start web for the search for documents. Only sites that are at this level or below will be searched.</param>
        /// <param name="docName">This is the name of the document library to look for in each site. In our case it is always “Background Information Library</param>
        /// <param name="fileName">This is file name to delete.</param>
        private void DelFileInDocLib(SPWeb web, string docName, string fileName)
        {
            foreach (SPList list in web.Lists)
            {
                if (list.BaseType == SPBaseType.DocumentLibrary)
                {
                    SPDocumentLibrary lib = list as SPDocumentLibrary;
                    if (lib.Title == docName)
                    {
                        List<string> filesToDelete = new List<string>();
                        foreach (SPListItem item in lib.Items)
                        {
                            SPFile file = null;

                            if (item.Name == fileName)
                            {
                                file = item.File;
                                if (file != null)
                                {
                                    filesToDelete.Add(file.Url);
                                    //Response.Write(String.Format("In DocLib: {0} ({2}) File - {1} ({3})", web.Title, item.Name, web.Url, file.Length));
                                }
                                break;
                            }
                        }

                        // Delete item
                        SPFolder folder = lib.ParentWeb.GetFolder(docName);
                        foreach (string url in filesToDelete)
                        {
                            folder.Files.Delete(url);
                            //Console.WriteLine("Deleted:" + url);
                        }
                        folder.Update();
                        lib.Update();
                    }
                }
            }
            //De quy de tim o cap thap hon
            //FindDocumentLibraries(web.Webs, name, operation);
        }

        private void BindDrop()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);

            // Bind Fields
            var dataField = from f in db.Fields
                            orderby f.Name
                            select f;
            ddlField.DataValueField = "Field_ID";
            ddlField.DataTextField = "Name";
            ddlField.DataSource = dataField;
            ddlField.DataBind();

            ddlField.Items.Insert(0, new ListItem("--Chọn lĩnh vực--", "-1"));

            // Bind Offices
            var dataOffice = from o in db.Offices
                             orderby o.Name
                             select new
                             {
                                 o.Office_ID,
                                 o.Name
                             };
            ddlOffice.DataValueField = "Office_ID";
            ddlOffice.DataTextField = "Name";
            ddlOffice.DataSource = dataOffice;
            ddlOffice.DataBind();

            ddlOffice.Items.Insert(0, new ListItem("--Chọn cơ quan--", "-1"));

            // Bind DocTypes
            var dataDocType = from o in db.DocumentTypes
                             orderby o.Name
                             select new
                             {
                                 o.DocType_ID,
                                 o.Name
                             };
            ddlDocType.DataValueField = "DocType_ID";
            ddlDocType.DataTextField = "Name";
            ddlDocType.DataSource = dataDocType;
            ddlDocType.DataBind();

            ddlDocType.Items.Insert(0, new ListItem("--Chọn loại văn bản--", "-1"));
        }

        private void LoadData()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            Document objAP = db.Documents.SingleOrDefault(a => a.Doc_ID == this.docId);
            if (objAP != null)
            {
                txtName.Text = objAP.Name;
                ddlField.SelectedValue = objAP.Field_ID.ToString();
                ddlOffice.SelectedValue = objAP.Office_ID.ToString();
                ddlDocType.SelectedValue = objAP.DocType_ID.ToString();
                txtDocNumber.Text = objAP.DocNumber;

                divAttachFile.Visible = false;
                fupAttach.Visible = true;
                if (objAP.AttachFile != null)
                {
                    if (objAP.AttachFile != "")
                    {
                        hplAttachFile.NavigateUrl = objAP.AttachFile;
                        hplAttachFile.Text = GetNameWithExtension(objAP.AttachFile);
                        divAttachFile.Visible = true;
                        fupAttach.Visible = false;
                    }
                }

                cbEffectStatus.Checked = objAP.EffectStatus;
            }
        }

        private void UpdateData()
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            Document objAP;

            if (this.modeform.Equals("u"))
                objAP = db.Documents.SingleOrDefault(a => a.Doc_ID == this.docId);
            else
                objAP = new Document();

            if (objAP == null) return;

            objAP.Name = txtName.Text;
            objAP.Field_ID = int.Parse(ddlField.SelectedValue);
            objAP.Office_ID = int.Parse(ddlOffice.SelectedValue);
            objAP.EffectStatus = cbEffectStatus.Checked;
            objAP.DocNumber = txtDocNumber.Text;
            objAP.DocType_ID = int.Parse(ddlDocType.SelectedValue);

            //Update attach file
            string path = UploadFiles();
            if (path != "")
            {
                objAP.AttachFile = path;
            }

            if (this.modeform.Equals("a"))
            {
                db.Documents.InsertOnSubmit(objAP);
            }

            db.SubmitChanges();

            Response.Redirect(CurrentUrlWithoutParam + "?page=AdminDoc");
        }

        private string GetNameWithExtension(string fullPath)
        {
            if (fullPath.LastIndexOf("/") != -1)
            {
                return fullPath.Substring(fullPath.LastIndexOf("/") + 1, fullPath.Length - fullPath.LastIndexOf("/") - 1);
            }
            else
            {
                return fullPath;
            }
        }

        private string GetUrlWithoutDomain(string strUrl)
        {
            if (strUrl.IndexOf("http://") == -1) return strUrl;

            strUrl = strUrl.Substring(7);
            return strUrl.Substring(strUrl.IndexOf("/"));
        }

        protected void lbtUpdate_Click(object sender, EventArgs e)
        {
            UpdateData();
        }

        protected void lbtDelFile_Click(object sender, EventArgs e)
        {
            HaNamAPDataDataContext db = new HaNamAPDataDataContext(Controler.HaNamAPConnectionString);
            Document obj = db.Documents.SingleOrDefault(d => d.Doc_ID == this.docId);
            if (obj != null)
            {
                //Delete file in doc libraries in sharepoint
                SPSite objSite = SPControl.GetContextSite(Context);
                SPWeb objWeb = objSite.OpenWeb();
                DelFileInDocLib(objWeb, "Documents", GetNameWithExtension(obj.AttachFile));
                
                // Xoa attach file trong db bang cach gan ""
                obj.AttachFile = "";
                db.SubmitChanges();

                divAttachFile.Visible = false;
                fupAttach.Visible = true;
            }
        }
    }
}